<template>
  <view class="task-management-page">
    <!-- 导航栏 -->
    <u-navbar title="任务管理" back-icon="arrow-left" />
    
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <u-input
          v-model="filterForm.taskName"
          placeholder="请输入任务名称"
          class="filter-input"
          @input="handleSearch"
        />
        <u-button 
          type="primary" 
          text="搜索" 
          size="mini"
          @click="handleSearch"
        />
      </view>
      <view class="filter-row">
        <u-picker
          :show="showTypePicker"
          :columns="typeColumns"
          @confirm="onTypeConfirm"
          @cancel="showTypePicker = false"
          title="选择任务类型"
        />
        <u-input
          v-model="filterForm.taskTypeText"
          placeholder="任务类型"
          readonly
          @click="showTypePicker = true"
          class="filter-input"
        />
        <u-picker
          :show="showStatusPicker"
          :columns="statusColumns"
          @confirm="onStatusConfirm"
          @cancel="showStatusPicker = false"
          title="选择状态"
        />
        <u-input
          v-model="filterForm.statusText"
          placeholder="状态"
          readonly
          @click="showStatusPicker = true"
          class="filter-input"
        />
      </view>
    </view>

    <!-- 列表区域 -->
    <scroll-view 
      scroll-y="true" 
      class="list-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <!-- 任务列表 -->
        <view 
          v-for="item in taskList" 
          :key="item.id"
          class="task-card"
          @click="goToTaskDetail(item.id)"
        >
          <view class="card-header">
            <view class="header-left">
              <text class="task-title">{{ item.taskName }}</text>
              <u-tag 
                :text="getTaskTypeText(item.taskType)" 
                type="info" 
                size="mini"
                class="type-tag"
              />
            </view>
            <view class="header-right">
              <u-tag 
                :text="getStatusText(item.status)" 
                :type="getStatusType(item.status)" 
                size="mini"
              />
            </view>
          </view>
          
          <view class="card-content">
            <view class="content-item">
              <u-icon name="location" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.areaName || '未分配区域' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="user" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.assignedUserName || '未分配人员' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="clock" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ formatDateTime(item.scheduledDate, item.scheduledTime) }}</text>
            </view>
            <view class="content-item" v-if="item.description">
              <u-icon name="file-text" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.description }}</text>
            </view>
          </view>
          
          <view class="card-footer">
            <view class="priority-info">
              <text class="priority-text">{{ getPriorityText(item.priority) }}</text>
              <view class="priority-bar">
                <view 
                  class="priority-fill"
                  :style="{ 
                    width: getPriorityPercentage(item.priority) + '%',
                    backgroundColor: getPriorityColor(item.priority)
                  }"
                ></view>
              </view>
            </view>
            
            <view class="action-buttons">
              <u-button 
                v-if="item.status === 1"
                type="primary" 
                text="分配"
                size="mini"
                @click.stop="goToTaskAssign(item.id)"
                class="action-btn"
              />
              <u-button 
                v-else-if="item.status === 2"
                type="success" 
                text="开始"
                size="mini"
                @click.stop="goToTaskStart(item.id)"
                class="action-btn"
              />
              <u-button 
                v-else
                type="info" 
                text="详情"
                size="mini"
                @click.stop="goToTaskDetail(item.id)"
                class="action-btn"
              />
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="taskList.length === 0 && !loading" class="empty-state">
          <u-empty text="暂无任务数据" icon="list" mode="list" />
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="taskList.length > 0" class="load-more-tip">
          <text v-if="loading" class="tip-text">加载中...</text>
          <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
          <text v-else class="tip-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 添加按钮 -->
    <view class="add-button" @click="goToTaskAdd">
      <u-icon name="plus" color="#fff" size="24"></u-icon>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getCleaningTaskPage } from '@/api/cleaning'

// 响应式数据
const taskList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  taskName: '',
  taskType: '',
  taskTypeText: '',
  status: '',
  statusText: ''
})

// 选择器显示状态
const showTypePicker = ref(false)
const showStatusPicker = ref(false)

// 选择器数据
const typeColumns = ref([[
  { label: '常规任务', value: 'routine' },
  { label: '临时任务', value: 'temporary' },
  { label: '特殊任务', value: 'special' }
]])

const statusColumns = ref([[
  { label: '待分配', value: 1 },
  { label: '已分配', value: 2 },
  { label: '进行中', value: 3 },
  { label: '已完成', value: 4 },
  { label: '已取消', value: 5 }
]])

// 页面加载时获取数据
onMounted(() => {
  loadTaskList()
})

/**
 * 加载任务列表
 */
const loadTaskList = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      pagination.pageNum = 1
      taskList.value = []
      hasMore.value = true
    }
    
    loading.value = true
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      taskName: filterForm.taskName,
      taskType: filterForm.taskType,
      status: filterForm.status
    }
    
    const response = await getCleaningTaskPage(params)
    if (response.success && response.data) {
      const { records, total } = response.data
      
      if (isRefresh) {
        taskList.value = records || []
      } else {
        taskList.value.push(...(records || []))
      }
      
      pagination.total = total || 0
      hasMore.value = taskList.value.length < pagination.total
    }
  } catch (error) {
    console.error('加载任务列表失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  loadTaskList(true)
}

/**
 * 类型选择确认
 */
const onTypeConfirm = (event) => {
  const selectedType = event.value[0]
  filterForm.taskType = selectedType.value
  filterForm.taskTypeText = selectedType.label
  showTypePicker.value = false
  loadTaskList(true)
}

/**
 * 状态选择确认
 */
const onStatusConfirm = (event) => {
  const selectedStatus = event.value[0]
  filterForm.status = selectedStatus.value
  filterForm.statusText = selectedStatus.label
  showStatusPicker.value = false
  loadTaskList(true)
}

/**
 * 下拉刷新
 */
const onRefresh = () => {
  refreshing.value = true
  loadTaskList(true)
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    pagination.pageNum++
    loadTaskList()
  }
}

/**
 * 获取任务类型文本
 */
const getTaskTypeText = (type) => {
  const typeMap = {
    'routine': '常规',
    'temporary': '临时',
    'special': '特殊'
  }
  return typeMap[type] || '未知类型'
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    1: '待分配',
    2: '已分配',
    3: '进行中',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'info',
    3: 'primary',
    4: 'success',
    5: 'error'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取优先级文本
 */
const getPriorityText = (priority) => {
  const priorityMap = {
    1: '低',
    2: '中',
    3: '高',
    4: '紧急'
  }
  return priorityMap[priority] || '未知'
}

/**
 * 获取优先级百分比
 */
const getPriorityPercentage = (priority) => {
  const percentageMap = {
    1: 25,
    2: 50,
    3: 75,
    4: 100
  }
  return percentageMap[priority] || 0
}

/**
 * 获取优先级颜色
 */
const getPriorityColor = (priority) => {
  const colorMap = {
    1: '#2ed573',
    2: '#ffa502',
    3: '#ff4757',
    4: '#ff3838'
  }
  return colorMap[priority] || '#747d8c'
}

/**
 * 格式化日期时间
 */
const formatDateTime = (date, time) => {
  if (!date) return ''
  const dateStr = date.toString()
  const timeStr = time ? time.toString() : ''
  return `${dateStr} ${timeStr}`
}

// 页面导航方法
const goToTaskDetail = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/cleaning-management/task-detail?id=${id}`
  })
}

const goToTaskAdd = () => {
  uni.navigateTo({
    url: '/pages/property-work/cleaning-management/task-add'
  })
}

const goToTaskAssign = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/cleaning-management/task-assign?id=${id}`
  })
}

const goToTaskStart = (id) => {
  console.log('goToTaskStart被调用，任务ID:', id)
  if (!id) {
    uni.showToast({
      title: '任务ID不能为空',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: `/pages/property-work/cleaning-management/task-start?id=${id}`,
    success: () => {
      console.log('页面跳转成功，任务ID:', id)
    },
    fail: (err) => {
      console.error('页面跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.task-management-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.filter-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-input {
      flex: 1;
    }
  }
}

.list-scroll {
  flex: 1;
  min-height: 0;
}

.list-content {
  padding: 20rpx;
}

.task-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .task-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .type-tag {
        flex-shrink: 0;
      }
    }
  }
  
  .card-content {
    margin-bottom: 20rpx;
    
    .content-item {
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .item-icon {
        flex-shrink: 0;
      }
      
      .item-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        word-break: break-all;
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .priority-info {
      flex: 1;
      
      .priority-text {
        display: block;
        font-size: 24rpx;
        color: #666;
        margin-bottom: 8rpx;
      }
      
      .priority-bar {
        width: 100%;
        height: 8rpx;
        background: #f0f0f0;
        border-radius: 4rpx;
        overflow: hidden;
        
        .priority-fill {
          height: 100%;
          border-radius: 4rpx;
          transition: width 0.3s ease;
        }
      }
    }
    
    .action-buttons {
      margin-left: 20rpx;
      
      .action-btn {
        min-width: 120rpx;
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.load-more-tip {
  padding: 30rpx 0;
  text-align: center;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.add-button {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.4);
  z-index: 999;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}
</style>
